package questionanswer;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;

public class OneAnswerFromMany implements Serializable, Answer {
    private String keyAnswer;
    private String[] answers;

    public OneAnswerFromMany(String keyAnswer, String[] answers) {
        this.keyAnswer = keyAnswer;
        this.answers = answers;
    }

    public OneAnswerFromMany(OneAnswerFromMany original) {
        int length = original.answers.length;
        this.keyAnswer = original.keyAnswer;
        this.answers = Arrays.copyOf(original.answers, length);
    }

    public void shuffleAnswers() {
        Collections.shuffle(Arrays.asList(answers));
    }

    @Override
    public String toString() {
        String result = "";
        for (int answerNumber = 0; answerNumber < answers.length; answerNumber++) {
             result += String.format("%d) %s%n", answerNumber + 1, answers[answerNumber]);
        }
        return result;
    }

    public boolean isCorrect(String userAnswer) {
        int choice = 0;
        try {
            choice = Integer.parseInt(userAnswer);
        } catch (NumberFormatException e){
            return false;
        }

        if ((choice < 1) || (choice > answers.length)) {
            return false;
        }

        int answerIndex = choiceToIndex(choice);

        return answers[answerIndex].equals(keyAnswer);
    }

    private int choiceToIndex(int choice) {
        return choice - 1;
    }
}
